<template>
  <div>
    <div>
      <a-card>
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" style="width: 100%;">
          <div>
            <h1>基本信息</h1>
            <a-form-model-item ref="activityName" label="活动名称:" prop="activityName">
              <a-input
                class="current"
                placeholder="请输入活动名称"
                :maxLength="20"
                v-model.trim="form.activityName"
                style="width:500px"
                @blur="
                  () => {
                    $refs.activityName.onFieldBlur()
                  }
                "
              /><span class="gray" style="white-space: nowrap;">限制20字以内，活动名称会在活动列表和移动端进行展示</span>
            </a-form-model-item>
            <a-form-model-item label="活动介绍:" prop="activityDesc">
              <a-input v-model="form.activityDesc" placeholder="请输入活动介绍" type="textarea" class="current" style="width:500px"/>
            </a-form-model-item>
            <a-form-model-item label="有效期:" prop="expireType">
              <a-radio-group @change="handleChange" v-model="form.expireType" style="width: 100%; margin-top: 3px">
                <div>
                  <a-radio :value="1"> 长期有效 </a-radio>
                  <a-date-picker
                    format="YYYY-MM-DD HH:mm:ss"
                    show-time
                    :value="form.expireType == 1 ? form.startTime : null"
                    @change="onChangeSTime"
                    :disabled-date="disabledDate"
                    placeholder="开始时间"
                    :disabled="form.expireType != 1"
                  />
                </div>
                <div class="row">
                  <a-radio :value="2"> 定时有效 </a-radio>
                    <a-date-picker
                      format="YYYY-MM-DD HH:mm:ss"
                      show-time
                      :value="form.expireType == 2 ? form.startTime : null"
                      @change="onChangeSTime"
                      :disabled-date="disabledDate"
                      placeholder="开始时间"
                      style="margin-right:30px"
                      :disabled="form.expireType != 2"
                    />
                    <a-date-picker
                      format="YYYY-MM-DD HH:mm:ss"
                      show-time
                      :value="form.expireType == 2 ? form.endTime : null"
                      @change="onChangeETime"
                      :disabled-date="disabledDate"
                      placeholder="结束时间"
                      :disabled="form.expireType != 2"
                    />
                </div>
              </a-radio-group>
            </a-form-model-item>
          </div>
          <a-divider dashed />
          <div>
            <h1>发券配置</h1>
            <a-form-model-item label="发券范围:" prop="sendVouRangeType">
              <a-radio-group v-model="form.sendVouRangeType" @change="handleChange('sendVouRangeType')">
                <a-radio :value="1"> 按门店 </a-radio>
                <a-radio :value="2"> 按导购 </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <div class="box" v-if="form.sendVouRangeType == '1'">
              <a-form-model-item label="选择门店:" prop="sendVouStoreType">
                <a-radio-group v-model="form.sendVouStoreType" style="width: 100%; margin-top: 8px" :disabled="isDisabled">
                  <a-radio class="radioBox" :value="1"> 所有门店 </a-radio>
                  <a-row :gutter="24" class="margintop" style="display: flex; align-items: center">
                    <a-radio :value="2" style="margin-left: 12px"> 部分门店</a-radio>
                    <a-select :disabled="form.sendVouStoreType != 2" v-model="form.sendVouRangeIds" mode="multiple" autoClearSearchValue show-search allowClear placeholder="请选择(可多选)" style="width: 50%"  prop="sendVouRangeIds">
                      <!-- @popupScroll="storeScroll" -->
                      <a-select-option  v-for="(item, index) in storePackageList" :key="index" :value="item.packageId"> {{ item.packageName }}</a-select-option>
                    </a-select>
                  </a-row>
                </a-radio-group>
              </a-form-model-item>
              <a-form-model-item prop="sendVoucherLimit">
                <span slot="label"><span class="requiredText">*</span>券包数量</span>
                <a-radio-group v-model="form.sendVoucherLimit.limitType" style="width: 70%; margin-top: 9px" :disabled="isDisabled">
                  <a-radio class="radioBox" :value="1"> 不限数量 </a-radio>
                  <a-row :gutter="24" style="display: flex; align-items: center; margin-left: 0px" class="margintop">
                    <a-radio :value="2"> 限制数量 </a-radio>
                    总量
                    <a-input-number :min="0"  style="width: 200px; margin: 0 20px" v-model="form.sendVoucherLimit.limitTotal" placeholder="输入个数" :disabled="disabledformLimit" />个
                  </a-row>
                  <a-row :gutter="24" class="margintop" style="display: flex; align-items: center">
                    <a-col :md="3" :sm="6"></a-col>
                    <a-select ref="select" placeholder="请选择" v-model="form.sendVoucherLimit.cycleType" style="width: 120px; margin-left: -12px" @change="handleChange" :disabled="disabledformLimit">
                      <a-select-option value="1">每天</a-select-option>
                      <a-select-option value="2">每周</a-select-option>
                    </a-select>
                    <a-input-number :min="0"  style="margin-right: 20px; margin-left: 60px" v-model="form.sendVoucherLimit.cycleLimitTotal" placeholder="输入个数"  :disabled="disabledformLimit" />
                    个
                  </a-row>
                  <a-row>
                    <a-col :md="2" :sm="6"></a-col>
                    <a-col :md="8" :sm="12">
                      <div class="gray" style="margin-left: 20px; margin-top: 10px;width:400px">
                        每个门店券包总数{{ form.sendVoucherLimit.limitTotal || 0 }}个，{{ form.sendVoucherLimit.cycleType == 1 ? '每天' : '每周' }}最多发出{{
                          form.sendVoucherLimit.cycleLimitTotal || 0
                        }}个
                      </div>
                    </a-col>
                  </a-row>
                  <div style="border-top: 1px solid #333; padding-top: 10px; margin-top: 20px">
                    <a-row style="display: flex">
                      <a-col :md="12" :sm="12">
                        <a-checkbox-group v-model="form.sendVouStoreTypeList" @change="onChange('model')">
                          <a-checkbox :value="3">根据导入模板进行限制</a-checkbox>
                        </a-checkbox-group>
                      </a-col>
                      <a-upload name="file" :showUploadList="false" :multiple="false" :action="importExcelUrl" :accept="'.xlsx,.xls'" @change="handleImportExcel1">
                        <a-button type="primary">{{ importBtnText }}</a-button>
                      </a-upload>
                      <a-button style="margin: 0 20px" type="primary" @click="exportExcel(0, '按门店发券导入模板', 1)">模板下载</a-button>
                      <a-button type="primary" :disabled="isStoreDown" @click="exportExcel(1, '按门店发券导入模板', 1)">文件下载</a-button>
                    </a-row>
              </div>
                </a-radio-group>
              </a-form-model-item>
            </div>
            <div class="box" v-if="form.sendVouRangeType == '2'">
              <a-form-model-item  prop="">
                <span slot="label"><span class="requiredText">*</span>添加导购</span>
                <div style="display: flex; align-items: center">
                  <a-select v-model="form.searchType" placeholder="请选择" style="width: 130px" :disabled="isDisabled">
                    <a-select-option v-for="(item, index) in guideType" :key="index" :value="item.code">{{ item.name }} </a-select-option>
                  </a-select>
                  <a-input v-model="form.searchValue" placeholder="输入导购工号" style="margin: 0 10px; width: 300px" :disabled="isDisabled" />
                  <a-button @click="addGuide" type="primary" style="margin-right: 10px" :disabled="isDisabled">添加</a-button>
                  <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :action="importExcelUrl" :accept="'.xlsx,.xls'" @change="handleImportExcel2">
                    <a-button type="primary">{{ importBtnText }}</a-button>
                  </a-upload>
                  <a-button type="primary" @click="exportExcel(2, '发券模板')" style="margin-left: 10px">模板下载</a-button>
                  <a-button :disabled="isGuideDown" type="primary" @click="exportExcel(1, '发券模板')" style="margin-left: 10px">文件下载</a-button> -->
                </div>
              </a-form-model-item>
              <div v-if="guideList.length > 0" style="width:1000px">
                <a-table
                  style="margin-left:20px"
                  :data-source="guideList"
                  :rowKey="
                    (record, index) => {
                      return index
                    }
                  "
                  :columns="columnsGuide"
                  :pagination="paginationProps"
                  :disabled="isDisabled"
                >
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a @click="deleteGuide(record)" :disabled="isDisabled">删除</a>
                    </template>
                  </span>
                </a-table>
              </div>
              <a-form-model-item prop="sendVoucherLimit.limitType">
                <span slot="label"><span class="requiredText">*</span>券包数量</span>
                <a-radio-group v-model="form.sendVoucherLimit.limitType" style="width: 70%; margin-top: 9px" :disabled="isDisabled">
                  <a-radio class="radioBox" :value="1"> 不限数量 </a-radio>
                  <a-row :gutter="24" style="display: flex; align-items: center; margin-left: 0px" class="margintop">
                    <a-radio :disabled="isDisabled" :value="2"> 限制数量 </a-radio>
                    总量
                    <a-input-number :min="0"  :disabled="disabledformLimit" style="margin: 0 10px" v-model="form.sendVoucherLimit.limitTotal" placeholder="输入个数" />个
                  </a-row>
                  <a-row :gutter="24" class="margintop" style="display: flex; align-items: center">
                    <a-col :md="3" :sm="6"></a-col>
                    <a-select :disabled="disabledformLimit" placeholder="请选择" ref="select" v-model="form.sendVoucherLimit.cycleType" style="width: 120px; margin-left: -10px" @change="handleChange">
                      <a-select-option value="1">每天</a-select-option>
                      <a-select-option value="2">每周</a-select-option>
                    </a-select>
                    <a-input-number :min="0"  :disabled="disabledformLimit" style=" margin: 0 20px 0 60px" v-model="form.sendVoucherLimit.cycleLimitTotal" placeholder="输入个数" />
                    个
                  </a-row>
                  <a-row style="display: flex">
                    <a-col :md="2" :sm="6"></a-col>
                    <div class="gray" style="margin-left: 20px; margin-top: 10px">
                      每个门店券包总数{{ form.sendVoucherLimit.limitTotal || 0 }}个，{{ form.sendVoucherLimit.cycleType == 1 ? '每天' : '每周' }}最多发出{{
                        form.sendVoucherLimit.cycleLimitTotal || 0
                      }}个
                    </div>
                  </a-row>
                  <div style="border-top: 1px solid #333; padding-top: 10px; margin-top: 20px">
                    <a-row style="display: flex">
                      <a-col :md="12" :sm="12">
                        <a-checkbox-group v-model="form.sendVouStoreTypeList" @change="onChange('model')">
                          <a-checkbox :value="3">根据导入模板进行限制</a-checkbox>
                        </a-checkbox-group>
                      </a-col>
                      <a-upload name="file" :showUploadList="false" :multiple="false" :action="importExcelUrl" :accept="'.xlsx,.xls'" @change="handleImportExcel1">
                        <a-button type="primary">{{ importBtnText }}</a-button>
                      </a-upload>
                      <a-button style="margin: 0 20px" type="primary" @click="exportExcel(0, '按导购发券导入模板', 2)">模板下载</a-button>
                      <a-button type="primary" :disabled="isStoreDown" @click="exportExcel(1, '按导购发券导入模板', 2)">文件下载</a-button>
                    </a-row>
              </div>
                </a-radio-group>
              </a-form-model-item>
            </div>
            
            <a-form-model-item label="发券方式" prop="shareVoucherTypeList">
              <a-checkbox-group style="margin-top: 10px" v-model="form.shareVoucherTypeList" @change="onChange">
                <a-row>
                  <a-checkbox :value="1" name="type"> 面对面扫码发券 </a-checkbox>
                </a-row>
                <a-row class="margintop">
                  <a-checkbox :value="2" name="type"> 分享发券 </a-checkbox>
                </a-row>
              </a-checkbox-group>
            </a-form-model-item>
            <a-form-model-item class="marginleft" prop="shareCardTitle">
              <span slot="label">自定义分享卡片</span>
              <a-input v-model="form.shareCardTitle" placeholder="请输入卡片标题" class="current" style="width:500px;"/>
              <div class="gray" style="line-height: 20px; margin-bottom: 20px">分享卡片标题，默认为活动标题</div>
              <JImageUpload
                :uploadParams="getUploadParams()"
                :isMultiple="false"
                :fileSize="2"
                :number="20"
                :accept="'image/*'"
                @fileChange="fileImageChange1"
                v-model="form.shareCardImage"
              ></JImageUpload>
              <div class="gray" style="line-height: 16px">小程序分享卡片图，不设置则默认展示小程序分享图片</div>
            </a-form-model-item>
            <a-form-model-item label="自定义分享海报:" prop="sharePosterImage" class="marginleft">
              <JImageUpload
                :uploadParams="getUploadParams()"
                :isMultiple="false"
                :fileSize="2"
                :number="20"
                :accept="'image/*'"
                @fileChange="fileImageChange2"
                v-model="form.sharePosterImage"
              ></JImageUpload>
              <div class="gray" style="line-height: 16px">图片用于生成领券活动二维码海报，图片建议尺寸 900x1200px，小于2mb，格式jpg、png。不设置则展示系统默认图。</div>
            </a-form-model-item>
          </div>
          <div>
            <h1>领券配置</h1>
            <a-form-model-item label="会员范围:" prop="receiveRangeType">
              <a-radio-group v-model="form.receiveRangeType" style="width: 100%" @change="handleChange('receiveRangeType')">
                <a-row :gutter="24" style="display: flex; align-items: center; height: 40px">
                    <a-radio :value="1" style="width:120px;margin-left:10px"> 全部会员</a-radio>
                </a-row>
                <a-row :gutter="24" class="margintop" style="display: flex; align-items: center; height: 40px">
                    <a-radio :value="2" style="width:120px;margin-left:10px"> 集团卡等级 </a-radio>
                    <a-select v-if="form.receiveRangeType == 2" style="width: 600px;" v-model="form.receiveRangeValue" placeholder="请选择" mode="multiple">
                      <a-select-option v-for="(item, index) in cardTypeList" :key="index" :value="item.id">{{ item.name }} </a-select-option>
                    </a-select>
                </a-row>
                <a-row :gutter="24" class="margintop" style="display: flex; align-items: center; height: 40px">
                    <a-radio :value="3" style="width:120px;margin-left:10px">品牌卡等级</a-radio>
                    <a-tree-select
                      v-if="form.receiveRangeType == 3"
                      v-model="form.receiveRangeValue"
                      style="width: 600px;margin-left:8px"
                      :dropdownStyle="{ maxHeight: '476px' }"
                      :tree-data="brandList"
                      tree-checkable
                      allowClear
                      placeholder="请选择"
                      :replaceFields="{ children: 'brandList', title: 'name', value: 'id' }"
                    />
                </a-row>
                <a-row :gutter="24" class="margintop" style="display: flex; align-items: center; height: 40px">
                    <a-radio :value="4" style="width:120px;margin-left:10px">人群包</a-radio>
                    <a-select v-if="form.receiveRangeType == 4" style="width: 600px;" v-model="form.receiveRangeValue" placeholder="请选择" mode="multiple">
                      <a-select-option v-for="(item, index) in peoplesPackageList" :key="index" :value="item.packageId">
                        {{ item.packageName }}
                      </a-select-option>
                    </a-select>
                </a-row>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="券包数量:" prop="receiveLimitType">
              <a-radio-group v-model="form.receiveLimitType" style="width: 100%; margin-top: 9px">
                <a-radio class="radioBox" :value="1"> 不限数量 </a-radio>
                <a-row :gutter="24" style="display: flex; align-items: center; margin-left: 0px" class="margintop">
                  <a-radio :value="2"> 限制数量 </a-radio>
                  总量
                  <a-input-number :disabled="disabledNum" :min="0"  style="width: 200px; margin: 0 20px" v-model="form.receiveVoucherLimit.limitTotal" placeholder="输入个数" />个
                </a-row>
                <a-row :gutter="24" class="margintop" style="display: flex; align-items: center">
                  <a-col :md="2" :sm="6"></a-col>
                  <a-select ref="select" :disabled="disabledNum" v-model:value="form.receiveVoucherLimit.cycleType" style="width: 120px; margin-left: -10px" @change="handleChange">
                    <a-select-option value="1">每天</a-select-option>
                    <a-select-option value="2">每周</a-select-option>
                  </a-select>
                  <a-input-number :min="0" :disabled="disabledNum" style="margin-left: 60px; margin-right: 20px" v-model="form.receiveVoucherLimit.cycleLimitTotal" placeholder="输入个数" />个
                </a-row>
                <a-row>
                  <a-col :md="2" :sm="6"></a-col>
                  <a-col :md="8" :sm="12">
                    <div class="gray" style="margin-top: 10px; margin-left: -20px;width:400px">
                      每人限制领取{{ form.receiveVoucherLimit.limitTotal || 0 }}个券包，每人{{ form.receiveVoucherLimit.cycleType == 1 ? '每天' : '每周' }}限制{{
                        form.receiveVoucherLimit.cycleLimitTotal || 0
                      }}个
                    </div>
                  </a-col>
                </a-row>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="领券页面:" prop="voucherReceiveTemplateId">
              <a-select ref="select" v-model:value="form.voucherReceiveTemplateId" style="width:480px;" @change="handleChange" placeholder="默认模板">
                <a-select-option v-for="(item, index) in voucherModelList" :key="item.id" :value="item.id" @popupScroll="vouScroll"> {{ item.templateName }}</a-select-option>
              </a-select>
              <a style="margin-left: 30px" @click="jump">自定义</a>
              <!-- <router-link style="margin-left:30px" :to="`/headquarters-coupon/addAndEditTemplate/null`">自定义
              </router-link> -->
            </a-form-model-item>
          </div>
          <div>
            <h1>券包配置</h1>
            <a-form-model-item label="关联优惠券:" prop="voucherRuleList">
              <a-row :gutter="24" style="display:flex">
                <a-col>
                  <a-input v-model="form.searchVouId" placeholder="输入优惠券ID" style="width:480px;" />
                </a-col>
                <a-col>
                  <a-button type="primary" @click="addVou" style="margin-left:30px">添加</a-button>
                </a-col>
              </a-row>
              <div style="margin-top:20px;width:900px">
                <a-table :data-source="form.voucherRuleList" :rowKey="(record, index) => index" :columns="columns" :pagination="paginationProps">
                  <span slot="ticket" slot-scope="text, record">
                    {{ record.type == '满减券' ? record.amount + '元' : record.discount * 10 + '折' }}
                  </span>
                  <span slot="voucherNum" slot-scope="text, record">
                    <a-input-number :min="0" v-model="record.voucherNum" style="width: 50%"></a-input-number>
                  </span>
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a style="margin-right: 20px" @click="showDetail(record)">查看</a>
                      <a @click="deleteVou(record)">删除</a>
                    </template>
                  </span>
                </a-table>
              </div>
            </a-form-model-item>
          </div>
        </a-form-model>
      </a-card>
      <div class="footer-box" v-if="!isCheck">
        <a-button @click="handleBack">取消</a-button>
        <a-button style="margin-left: 8px" @click="preservation" type="primary">创建</a-button>
      </div>
    </div>
    <vouDetail :vouVisible.sync="vouVisible" ref="vouDetail" :detail="voucherDetail"></vouDetail>
    <add-guide ref="addguide"  :selected="guideList" :guideVisible.sync="guideVisible" :loadData="sendVouGuide" @handleOk="editGuide"> </add-guide>
    <a-modal :visible="visibleTip" :width="600" @cancel="visibleTip = false" @ok="visibleTip = false">
      <div class="edit-activity">{{ tipText }}</div>
    </a-modal>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { storeCouponDetail, cardType, storePackage, voucherModel, editVoucher, searchVou, exportExcel, searchGuide, editActive, inportVerify } from '@/api/marketingCenter/storeCoupon.js'
import { queryExportSuccess } from '@/assets/js/common'
import { STable } from '@views/box/components'
import vouDetail from '@/views/marketingCenter/storeCoupon/components/vouDetail'
import addGuide from '@/views/marketingCenter/storeCoupon/components/addGuide'
import globalData from '@/assets/js/common'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import ImgUpload from '@/views/pos+/match/collocation/components/JImageUpload.vue'
import { number, string } from 'mathjs'
import { axios } from '@/utils/request'
const columns = [
  {
    title: '券模板ID',
    dataIndex: 'awardId',
    align: 'left',
  },
  {
    title: '券名称',
    dataIndex: 'voucherName',
   align: 'left',
  },
  {
    title: '面值',
    dataIndex: 'ticket',
    scopedSlots: { customRender: 'ticket' },
   align: 'left',
  },
  {
    title: '券类型',
    dataIndex: 'type',
   align: 'left',
  },
  {
    title: '券包张数',
    dataIndex: 'voucherNum',
    scopedSlots: { customRender: 'voucherNum' },
    align: 'left',
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
]
const columnsGuide = [
  {
    title: '导购名称',
    dataIndex: 'rangeName',
    align: 'left',
  },
  {
    title: '导购工号',
    dataIndex: 'rangeId',
    align: 'left',
  },
  {
    title: '导购手机号',
    dataIndex: 'guideTel',
    align: 'left',
  },
  {
    title: '导购店铺',
    dataIndex: 'guideStore',
    align: 'left',
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    JImageUpload,
    ImgUpload,
    STable,
    vouDetail,
    addGuide
  },
  data() {
    let validateBrand = (rule, value, callback) => {
      conosle.log(value, '品牌')
      if (this.brandId && this.brandId.length < 1) {
        callback(new Error('请选择适用品牌'))
      } else {
        callback()
      }
    }
    const range = (start, end) => {
      const result = []
      for (let i = start; i < end; i++) {
        result.push(i)
      }
      return result
    }
    const disabledDate = current => {
      return current && current < dayjs().startOf('day')
    }
    return {
      uploadUrl: 'https://jic.jnby.com/',
      brandId: [
        {
          value: '2738574294',
          label: 'JNBY'
        },
        {
          value: '2822095692',
          label: 'LESS'
        },
        {
          value: '2504948039',
          label: 'CROQUIS'
        },
        {
          value: '4',
          label: 'JNBY BY JNBY'
        },
        {
          value: '8348044436',
          label: 'JNBYHOME'
        },
        {
          value: '6924108367',
          label: 'POMME DE TERRE'
        },
        {
          value: '15',
          label: 'APN73'
        }
      ],
      brandList: [], // 品牌卡
      cardTypeList: [],
      peoplesPackageList: [], // 人群包
      storePackageList: [], // 门店包
      voucherModelList: [], // 领券模板

      disabledDate,
      columns,
      columnsGuide,

      currentEditIndex: '',
      imgList: [],
      visibleImg: false,
      // id: this.$route.params.id,
      id: '',
      labelCol: { span: 3 },
      wrapperCol: { span: 18 },
      visible: false,
      tipVisible: false, // 提示框
      frameVisible: false,
      // productList: [],
      form: {
        activityName: '',
        activityDesc: '',
        expireType: '',
        startTime: null,
        endTime: null,
        sendVouRangeType: '',
        sendVouStoreType: '',
        sendVouRangeIds: [],
        sendVouStoreTypeList: [],
        shareVoucherType: '',
        shareVoucherTypeList: [],
        receiveRangeType: '',
        receiveRangeValue: [],
        receiveLimitType: '',
        receiveCycleLimitType: '',
        receiveLimitTotal: '',
        voucherReceiveTemplateId: '',
        voucherRuleList: [],
        isModel: false,
        sendVoucherLimit: {
          cycleLimitTotal: '',
          cycleType: '',
          limitTotal: '',
          limitType: ''
        },
        receiveVoucherLimit: {
          cycleLimitTotal: '',
          cycleType: '',
          limitTotal: '',
          limitType: ''
        },
        searchType: undefined,
        searchValue: undefined,
      },
      rules: {
        activityName: [
          { required: true, message: '请填写活动名称', trigger: 'blur' },
          { max: 20, message: '活动名称长度限制20字内', trigger: 'blur' }
        ],
        activityDesc: [
          { required: true, message: '请填写活动介绍', trigger: 'blur' },
          { max: 200, message: '活动介绍文案长度限制200字内', trigger: 'blur' }
        ],
        expireType: [{ required: true, message: '请选择有效期', trigger: 'blur' }],
        // startTime: [{ required: true, message: '请选择活动开始时间', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择活动结束时间', trigger: 'blur' }],
        sendVouRangeType: [{ required: true, message: '请选择发券范围', trigger: 'blur' }],
        // sendVoucherLimit: [{ required: true, message: '请填写券包数量', trigger: 'blur' }], // 发券配置
        sendVouStoreType: [{ required: true, message: '请选择发券门店类型', trigger: 'blur' }],
        shareVoucherTypeList: [{ required: true, message: '请选择发券方式', trigger: 'blur' }],
        receiveRangeType: [{ required: true, message: '请选择领券会员范围', trigger: 'blur' }],
        receiveRangeValue: [{ required: true, message: '请选择领券会员等级', trigger: 'blur' }],
        receiveLimitType: [{ required: true, message: '请选择会员领券限制类型', trigger: 'blur' }],
        receiveCycleLimitType: [{ required: true, message: '请选择会员领券周期性限制类型', trigger: 'blur' }],
        receiveLimitTotal: [{ required: true, message: '请填写每个会员限制领券的总数', trigger: 'blur' }],
        voucherReceiveTemplateId: [{ required: true, message: '请选择领券页模板', trigger: 'blur' }],
        voucherRuleList: [{ required: true, message: '请选择关联优惠券', trigger: 'blur' }]
        // putChannel: [
        //   {
        //     type: 'array',
        //     required: true,
        //     message: '请选择可见渠道',
        //     trigger: 'change'
        //   }
        // ]
      },
      fileList: [],
      userInfo: Vue.ls.get(USER_INFO),
      isCheck: false,
      paginationProps: {
        pageSize: 10,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      storePage: 1,
      peoplePage: 1,
      vouPage: 1,
      fileList: [],
      importUrl: '',
      importExcelUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
      voucherDetail: {},
      vouVisible: false,
      guideVisible: false,
      guideType: [
        {
          name: '工号',
          code: 'code'
        },
        {
          name: '手机号',
          code: 'tel'
        }
      ],
      queryParam: {},
      timer: null,
      sendVouGuide: [],
      guideList: [],
      isDisabled: false,
      id: '',
      visibleTip: false,
      tipText: '',
      importBtnText: '导入'
      // editimgKey: ''
    }
  },
  computed: {
    disabledformLimit(){
      return this.disabled || this.form.sendVoucherLimit.limitType != 2
    },
    disabledNum(){
      return this.form.receiveLimitType != 2
    },
    disabledStore(){
      return this.disabled || this.form.sendVouStoreType != 2
    },
    isStoreDown() {
      // 门店发券 不是新增  已经上传
      // if (this.$route.params.id == 'add' || this.form.sendVouRangeType != 1 || this.originSendVouRangeType == 2 || this.originSendVouStoreType != 3 || this.form.sendVouStoreType != 3) {
      //   console.log('==true==')
      //   return true
      // } else {
      //   console.log('==false==')
      //   return false
      // }
      return !this.form.sendVouStoreTypeList.includes(3) || this.$route.params.id == 'add'
    },
    isGuideDown() {
      console.log('====', this.$route.params.id)
      console.log('====', this.form.sendVouRangeType)
      if (this.$route.params.id == 'add' || this.form.sendVouRangeType != 2 || this.originSendVouStoreType != 3 || this.originSendVouRangeType == 1) {
        return true
      } else {
        return false
      }
    }
  },
  async mounted() {
    await this.getCardType(true)
    await this.getCardType(false)
    this.getPackage(true)
    this.getPackage(false)
    this.getVoucherModel()
    if (sessionStorage.getItem('vouOriginData')) {
      this.form = JSON.parse(sessionStorage.getItem('vouOriginData'))
      if(sessionStorage.getItem('vouOriginGuide')){
        this.guideList = JSON.parse(sessionStorage.getItem('vouOriginGuide'))
      }
      return
    }
    // 复制 add?57
    let index = this.$route.params.id.indexOf('-')
    let id = this.$route.params.id
    if (index > 0) {
      // 复制
      this.copyId = id.substring(index + 1)
      await this.postDetail('copy')
    } else {
      if (id != 'add') {
        // 编辑
        this.id = id
        await this.postDetail()
      }
    }
    // await this.getCardType(true)
    // await this.getCardType(false)
    // this.getPackage(true)
    // this.getPackage(false)
    // this.getVoucherModel()
  },
  created() {
    console.log('created add guide')
  },

  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  watch: {
    isDisabled(val) {
      if(val){
        this.guideList = []
        this.form.searchType = undefined
        this.form.searchValue = undefined
      }
    }
  },
  methods: {
    // 跳转
    jump() {
      console.log('====', this.form)
      sessionStorage.setItem('vouOriginData', JSON.stringify(this.form))
      sessionStorage.setItem('vouOriginGuide', JSON.stringify(this.guideList))
      this.$router.push('/headquarters-coupon/addAndEditTemplate/null')
    },
    // 删除优惠券
    async deleteVou(val) {
      const that = this
      this.form.voucherRuleList.map((item, index) => {
        if (val.awardId == item.awardId) {
          that.form.voucherRuleList.splice(index, 1)
        }
      })
    },
    // 添加导购
    async addGuide() {
      if (!this.form.searchType || !this.form.searchValue) {
        this.$message.warning('请补全搜索信息')
        return
      }
      const obj = {
        guideTel: this.form.searchType == 'tel' ? this.form.searchValue : '',
        rangeId: this.form.searchType == 'code' ? this.form.searchValue : ''
      }
      const res = await searchGuide(obj)
      if (res.code == 200) {
        this.guideVisible = true
        this.sendVouGuide = res.data
      } else {
        this.$message.error(res.msg)
      }
    },
    
    editGuide(val) {
      this.guideVisible = false
      let arr = this.guideList
      // arr = arr.concat(val)
      // var newArr = arr.filter((x, index) => {
      //   var arrids = []
      //   arr.forEach((item, i) => {
      //     arrids.push(item.guideId)
      //   })
      //   const ret = arrids.indexOf(x.guideId) == index
      //   return ret
      // })
      if(val.length > 0){
        val.forEach(item => {
          if(!arr.find(x => x.guideId == item.guideId)){
            arr.push(item)
          }
        })
      }
      this.guideList = arr
    },
    deleteGuide(val) {
      const that = this
      let arr = JSON.parse(JSON.stringify(this.guideList))
      arr.map((item, index) => {
        if (item.guideId == val.guideId) {
          arr.splice(index, 1)
        }
      })
      this.guideList = arr
      console.log(this.$refs.addGuide)
      if(this.$refs.addGuide){
        this.$refs.addGuide.selectedRowKeys = arr.map(item => item.guideId)
      }
      console.log('=====00==', this.guideList)
    },

    // 券包-添加券
    async addVou() {
      const that = this
      if (!this.form.searchVouId.trim()) {
        this.$message.warning('请输入有效模板ID')
        return
      }
      const res = await searchVou(this.form.searchVouId)
      if (res.code == 200) {
        if (res.data.length == 0) {
          this.$message.error('请输入有效模板ID')
          return
        }
        res.data.map(item => {
          Object.assign(item, {
            voucherNum: 1
          })
        })
        let result = res.data
        console.log('====', result)
        if (this.form.voucherRuleList.length > 0) {
          let filterArr = this.form.voucherRuleList.filter(item => item.awardId == result[0].awardId)
          if (filterArr.length > 0) {
            this.form.voucherRuleList.map(item => {
              if (item.awardId == result[0].awardId) {
                item.voucherNum++
              }
            })
          } else {
            that.form.voucherRuleList.push(result[0])
          }
        } else {
          this.form.voucherRuleList = result
        }

        console.log('===00=', this.form.voucherRuleList)
      } else {
        this.$message.error(res.msg)
      }
    },
    showDetail(val) {
      this.voucherDetail = val
      this.vouVisible = true
    },
    //上传文件改变时  发券模板/导购
    async handleImportExcel1(file) {
      let res = file.file.response
      if (res) {
        if (res.code == 200) {
          let obj = {
            sendVouRangeExcelUrl: res.data,
            sendVouRangeType: this.form.sendVouRangeType
          }
          const result = await inportVerify(obj)
          console.log('=====', result)
          if (result.code == 200) {
            this.form.sendVouRangeExcelUrl = res.data
            this.importBtnText = '重新导入'
            this.form.sendVouStoreTypeList = [3]
            this.form.sendVouStoreType = '3'
            this.isDisabled = true
            this.form.sendVouRangeIds = []
            this.form.limitType = ''
            this.form.sendVoucherLimit = {
              cycleLimitTotal: '',
              cycleType: '',
              limitTotal: '',
              limitType: ''
            }
            this.$message.success('上传成功！')
          } else {
            // this.$message.error(result.msg)
            this.visibleTip = true
            this.tipText = result.msg
          }
        } else {
          this.$message.error('上传失败！')
        }
      }
    },
    async handleImportExcel2(file) {
      let res = file.file.response
      if (res) {
        if (res.code == 200) {
          let obj = {
            sendVouRangeExcelUrl: res.data,
            sendVouRangeType: 2
          }
          const result = await inportVerify(obj)
          console.log('=====', result)
          if (result.code == 200) {
            this.form.sendVouRangeExcelUrl = res.data
            this.importBtnText = '重新导入'
            this.$message.success('上传成功！')
          } else {
            this.$message.error(result.msg)
          }
        } else {
          this.$message.error('上传失败！')
        }
      }
    },
    onChange(val) {
      if (val == 'model') {
        if (this.form.sendVouStoreTypeList[0] == 3) {
          this.form.sendVouStoreType = '3'
          this.isDisabled = true
          this.form.sendVouRangeIds = []
          this.form.limitType = ''
          this.form.sendVoucherLimit = {
            cycleLimitTotal: '',
            cycleType: '',
            limitTotal: '',
            limitType: ''
          }
        } else {
          this.isDisabled = false
        }
      }
    },
    // 回显
    postDetail(isCopy) {
      const that = this
      storeCouponDetail(isCopy ? this.copyId : this.id).then(res => {
        if (res.code == 200) {
          console.log('回显', res.data)
          let info = res.data
          that.form.activityName = info.activityName
          that.form.activityDesc = info.activityDesc
          that.form.expireType = info.expireType // 有效期(1:长期有效;2:定时有效)
          if (info.expireType == 1) {
            that.form.startTime = info.startTime
          } else {
            that.form.startTime = info.startTime
            that.form.endTime = info.endTime
          }
          that.form.sendVouRangeType = info.sendVouRangeType //发券范围类型(1：按门店 2：按导购)
          that.originSendVouRangeType = info.sendVouRangeType // 原始发券类型
          that.originSendVouStoreType = info.sendVouStoreType // 原始发券类型
          if (info.sendVouRangeType == 1) {
            that.form.sendVouStoreType = info.sendVouStoreType // 门店类型（1：所有门店；2：指定门店包/导购；3：导入）
            if (info.sendVouStoreType == 3) {
              // 所有门店——导入
              this.form.sendVouStoreTypeList = [3]
              this.isDisabled = true
            }
          } else if (info.sendVouRangeType == 2) {
            
            if(info.sendVouStoreType == 3){
              this.form.sendVouStoreType = info.sendVouStoreType
              this.form.sendVouStoreTypeList = [3]
              this.isDisabled = true
            }else{
              that.guideList = info.guideList // 导购列表
            }
          } else {
            // 导入
            that.form.sendVouStoreTypeList = [info.sendVouStoreType]
            that.isDisabled = true
          }
          // 门店包
          if (info.storePackList.length > 0) {
            this.form.sendVouRangeIds = info.storePackList
          }
          if (info.sendVouLimitParams && info.sendVouLimitParams != 'null' && info.sendVouLimitParams != null) {
            that.form.sendVoucherLimit = JSON.parse(info.sendVouLimitParams) // 发券限制条件参数
            let cycleType = JSON.parse(info.sendVouLimitParams).cycleType
            if (cycleType) {
              that.form.sendVoucherLimit.cycleType = cycleType.toString()
            }
            console.log('发券限制条件参数===', JSON.parse(info.sendVouLimitParams))
          }

          that.form.shareVoucherTypeList = info.shareVoucherTypeList // 1：面对面扫码发券；2：分享发券
          that.form.shareCardTitle = info.shareCardTitle // 自定义分享卡片标题
          that.form.shareCardImage = info.shareCardImage
          that.form.sharePosterImage = info.sharePosterImage
          that.form.receiveRangeType = info.receiveRangeType // 会员范围：1：全部会员；2：集团卡等级；3：品牌卡等级；4：人群包
          if (info.receiveRangeType != 1) {
            // 领券会员范围
            if (info.receiveRangeType == 2 || info.receiveRangeType == 2) {
              that.form.receiveRangeValue = info.receiveRangeValue.split(',').map(Number)
            } else {
              that.form.receiveRangeValue = info.receiveRangeValue.split(',')
            }
            console.log('==领券会员范围', that.form.receiveRangeValue)
          }
          that.form.voucherPackNum = info.voucherPackNum // 券包总数
          // 会员领券限制数量
          that.form.receiveLimitType = info.receiveLimitType // 会员领券限制类型（1：不限制数量；2：限制数量）
          if (info.receiveLimitType == 2) {
            that.form.receiveVoucherLimit.limitTotal = info.receiveLimitTotal
            that.form.receiveVoucherLimit.cycleType = info.receiveCycleLimitType.toString() // 会员领券周期性限制类型（1：每天；2：每周）
            that.form.receiveVoucherLimit.cycleLimitTotal = info.receiveCycleLimitTotal // 会员领券每天/周限制领取数量
          }
          that.form.voucherReceiveTemplateId = info.voucherReceiveTemplateId // 领券页模板id
          that.form.voucherRuleList = info.voucherRuleList
          console.log('===回显数据===', that.form)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleProvinceChange(value) {
      let list = this.leafClassifyList.filter(item => item.pidCode == value)
      this.copyList = list.filter(item => this.copyIdList.includes(item.code))

      this.form.cation = null
    },
    handleChange(tag, val) {
      if (tag == 'receiveRangeType') {
        this.form.receiveRangeValue = []

      }
      if (tag == 'sendVouRangeType') {
        this.form.sendVouRangeExcelUrl = ''
        this.importBtnText = '导入'
      }
    },
    onChangeSTime(date, dateString) {
      this.form.startTime = dateString
    },
    onChangeETime(date, dateString) {
      let begin = new Date(this.form.startTime.replace(/-/g, '/'))
      let end = new Date(dateString.replace(/-/g, '/'))
      if (begin - end > 0) {
        this.$message.error('结束时间不能早于开始时间')
        this.form.endTime = null
        return
      } else {
        this.form.endTime = dateString
      }
    },
    fileImageChange1(list) {
      this.form.shareCardImage = list.length > 0 ? list[0].url : ''
    },
    fileImageChange2(list) {
      this.form.sharePosterImage = list.length > 0 ? list[0].url : ''
    },
    // 上传图片
    getUploadParams() {
      return {
        ...globalData.uploadParams
      }
    },
    fileChange(list) {
      this.fileList = list
    },
    handleBack() {
      this.$router.back()
    },
    preservation() {
      console.log('=提交参数==', this.form)
      // if (this.form.sendVouRangeType == '2') {
      //   if (this.form.sendVouRangeExcelUrl) {
      //     this.form.sendVouStoreType = '3'
      //   } else {
      //     this.form.sendVouStoreType = '2'
      //   }
      // }
      // this.form.startTime = this.form.startTime.format('YYYY-MM-DD HH:mm')
      const that = this
     
      // 发券范围-按门店
      if (that.form.sendVouRangeType == 1 && that.form.sendVouStoreType == 2 && that.form.sendVouRangeIds.length == 0) {
        that.$message.error('未指定门店或导购!')
        return
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log(this.form,'==提交参数==')
          if (that.form.expireType == 1) {
            if (!this.form.startTime) {
              this.$message.error('请选择开始时间！')
              return
            }
          } else {
            if (!that.form.startTime || !that.form.endTime) {
              that.$message.error('请选择完整时间范围！')
              return
            }
          }
          // 当前是否是导入
          const isImport = that.form.sendVouStoreTypeList.includes(3)
          // 手动添加导购
          if (that.form.sendVouRangeType == '2' && !isImport) {
            // 按导购
            let hasGuide = that.guideList.length > 0
            if (!hasGuide) {
              return that.$message.error('请添加导购！')
            }
          }
          // 发券范围-按导购
          if(that.form.sendVouRangeType == '2'){
            that.form.sendVouStoreType = isImport ? 3 : 2
          }
          
          // 券包数量-发券
          if (that.form.sendVouStoreType != 3 && !isImport) {
            let result = that.form.sendVoucherLimit
            if (!result.limitType) {
              return that.$message.error('请选择券包数量！')
            }
            if (result.limitType == 2 && (!result.limitTotal || !result.cycleType || !result.cycleLimitTotal)) {
              that.$message.error('请补全券包数量要求！')
              return
            }
          }
          // 领券——会员范围
          if (that.form.receiveRangeType != 1) {
            if (that.form.receiveRangeValue.length == 0) {
              that.$message.error('未指定领券会员范围')
              return
            }
          }
          // 券包数量-领券
          if (that.form.receiveLimitType == 2) {
            let result2 = that.form.receiveVoucherLimit
            if (!result2.limitTotal || !result2.cycleType || !result2.cycleLimitTotal) {
              that.$message.error('请补全领券券包数量要求！')
              return
            }
            that.form.receiveVoucherLimit.limitType = that.form.receiveLimitType
          }
          that.editVoucherPost()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 创建、编辑
    async editVoucherPost() {
      // 导购
      Object.assign(this.form, {
        operatorDto: {
          operatorId: this.$store.getters.userInfo.id,
          operatorName: this.$store.getters.userInfo.realname
        }
      })
      if (this.form.sendVouRangeType == '2') {
        // 按导购 导购ids
        let arr = this.guideList.map(item => {
          return item.guideId
        })
        this.form.sendVouRangeIds = arr
      }
      if (this.form.expireType == 1) {
        this.form.endTime = null
      }
      if (this.form.sendVouStoreType == 3) {
        // 导入文件
        delete this.form.sendVoucherLimit
      }
      // 发券
      if (this.form.sendVouRangeType == 2 && this.form.sendVouRangeExcelUrl) {
        delete this.form.sendVoucherLimit
      }
      this.form.shareVoucherType = this.form.shareVoucherTypeList.join(',')
      delete this.form.shareVoucherTypeList
      // 关联的优惠券
      this.form.voucherPackList = this.form.voucherRuleList
      delete this.form.voucherRuleList
      delete this.form.sendVouStoreTypeList
      delete this.form.isModel
      delete this.form.searchVouId
      console.log('===', this.form)
      let paramData = JSON.parse(JSON.stringify(this.form))
      // 发券
      if (paramData.sendVouRangeType == 2 && paramData.sendVouRangeExcelUrl) {
        delete paramData.sendVoucherLimit
      }
      let obj = paramData

      if (this.id && this.id != 'add') {
        // 编辑
        Object.assign(obj, {
          id: this.id
        })
      } else if (this.copyId) {
        // 复制
        Object.assign(obj, {
          copyId: this.copyId
        })
      }
      if (obj.receiveRangeValue.length > 1) {
        obj.receiveRangeValue = paramData.receiveRangeValue.join(',')
      } else {
        obj.receiveRangeValue = paramData.receiveRangeValue[0]
      }

      const res = await editVoucher(obj)
      if (res.code == 200) {
        // this.$message.success(this.id != 'add' ? '编辑成功!' : '创建成功!')
        this.$message.success('提交成功!')
        this.$router.back()
      } else {
        this.$message.error(res.msg)
      }
    },
    application() {},

    // 券模板
    vouScroll(e) {
      const { target } = e
      const scrollHeight = target.scrollHeight - target.scrollTop
      const clientHeight = target.clientHeight
      if (scrollHeight < clientHeight + 5) {
        this.vouPage++
        if (this.vouPage > this.totalVouPage) {
          return
        } else {
          this.getVoucherModel()
        }
      }
    },
    // 获取卡等级
    getCardType(val) {
      const that = this
      cardType(val).then(res => {
        if (res.code == 200) {
          if (val) {
            that.cardTypeList = res.data
          } else {
            res.data.map((item, index) => {
              Object.assign(item, {
                name: item.brandName,
                id: index
              })
            })
            that.brandList = res.data
          }
        }
      })
    },
    getPackage(val) {
      const that = this
      storePackage(val).then(res => {
        if (res.code == 200) {
          let result = res.data
          if (val) {
            // 门店包
            that.storePackageList = result
          } else {
            // 人群包
            that.peoplesPackageList = result
          }
        }
      })
    },
    // 获取领券模板
    getVoucherModel() {
      const that = this
      let obj = {
        current: this.vouPage,
        size: 50
      }
      voucherModel(obj).then(res => {
        if (res.code == 200) {
          let result = res.data
          that.totalVou = result.total
          that.totalVouPage = parseInt(result.total / result.size) + 1
          if (this.vouPage == 1) {
            that.voucherModelList = result.records
          } else {
            that.voucherModelList = that.voucherModelList.concat(result.records)
          }
        }
      })
    },
    // 下载
    async exportExcel(val, fileName, type) {
      const obj = {
        actId: this.copyId ? this.copyId : this.id, // 编辑、复制
        isTemplate: val == 1 ? false : true,
        sendRangeType: type == 2 ? 2 : 1
      }
      const data = await exportExcel(obj)
      if (!data) {
        this.$message.warning('文件下载失败')
        return
      } else {
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
/deep/ .ant-tag-checkable {
  border: 1px solid #ccc;
}

.current {
  width: 800px;
}

.radioBox {
  display: block;
}

.margintop {
  margin-top: 12px;
}

.box {
  margin-left: 120px;
}

.marginleft {
  margin-left: 160px;
}

.gray {
  color: #aaaaaa;
}

.row {
  margin-top: 20px;
  display: flex;
}

.product-wrapper {
  display: flex;

  .img {
    display: block;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
  }

  .text {
    flex: 1;
    margin-left: 10px;
    line-height: 20px;
    font-size: 12px;
    color: #333;
    min-width: 240px;

    .t {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      word-break: break-all;
      /* 追加这一行代码 */
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
    }
  }
}

.footer-box {
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.1);
  position: relative;
  background-color: #fff;
  height: 60px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/deep/ .ant-anchor-ink::before {
  background-color: transparent;
}

.edit-activity {
  margin: 24px 0 12px 0;
  font-weight: 500;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}
input {
  -moz-appearance: textfield;
}
.requiredText{
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
</style>
